/*
 * GArchivedMatch.java
 * Created on 19 oct. 2008
 *
 * Glacéo Internet Platform
 * http://sourceforge.net/projects/chm/
 *
 * Copyright (c) 2005-2009, Jens and Jan Janke (VirtualHockey Project)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hockeo.vhbase.data.dao.match;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import com.hockeo.vhbase.data.dao.IGEntity;
import com.hockeo.vhbase.data.dao.club.GClub;
import com.hockeo.vhbase.data.dao.season.GSeason;
import com.hockeo.vhbase.data.helper.GArchivedMatchType;
import com.hockeo.vhbase.data.helper.GMatchResult;
import com.hockeo.vhbase.data.helper.GMatchType;

/**
 * Represents a match from a previous season that has been archived.
 *
 * @version $Id$
 * @author jjanke
 */
@Entity
@Table( name = "a_match" )
public class GArchivedMatch implements IGEntity
{
  @Id
  @Column( name = "id" )
  @GeneratedValue( strategy = GenerationType.AUTO )
  private int                d_nId;

  @Enumerated( EnumType.STRING )
  @Column( name = "archive_type" )
  private GArchivedMatchType d_archiveType;

  @ManyToOne( fetch = FetchType.LAZY )
  @JoinColumn( name = "season_id" )
  private GSeason            d_season;

  @Column( name = "contest_element_id" )
  private String             d_strContestElementId;

  @Column( name = "round_num" )
  private int                d_nRoundNum;

  @Column( name = "matchday_num" )
  private int                d_nMatchdayNum;

  @ManyToOne( fetch = FetchType.LAZY )
  @JoinColumn( name = "club_home_id" )
  private GClub              d_clubHome;

  @ManyToOne( fetch = FetchType.LAZY )
  @JoinColumn( name = "club_away_id" )
  private GClub              d_clubAway;

  @Column( name = "goals_home" )
  private int                d_nGoalsHome         = 0;

  @Column( name = "goals_away" )
  private int                d_nGoalsAway         = 0;

  @Column( name = "goals_shootout_home" )
  private int                d_nGoalsShootoutHome = 0;

  @Column( name = "goals_shootout_away" )
  private int                d_nGoalsShootoutAway = 0;

  @Column( name = "points_home" )
  private int                d_nPointsHome        = 0;

  @Column( name = "points_away" )
  private int                d_nPointsAway        = 0;

  /** Default parameterless constructor. */
  protected GArchivedMatch()
  {}

  public GArchivedMatchType getArchiveType()
  {
    return d_archiveType;
  }

  public GSeason getSeason()
  {
    return d_season;
  }

  public String getContestElementId()
  {
    return d_strContestElementId;
  }

  public int getRoundNum()
  {
    return d_nRoundNum;
  }

  public int getMatchdayNum()
  {
    return d_nMatchdayNum;
  }

  public GClub getClubHome()
  {
    return d_clubHome;
  }

  public GClub getClubAway()
  {
    return d_clubAway;
  }

  public int getGoalsHome()
  {
    return d_nGoalsHome;
  }

  public int getGoalsAway()
  {
    return d_nGoalsAway;
  }

  public int getGoalsShootoutHome()
  {
    return d_nGoalsShootoutHome;
  }

  public int getGoalsShootoutAway()
  {
    return d_nGoalsShootoutAway;
  }

  public int getPointsHome()
  {
    return d_nPointsHome;
  }

  public int getPointsAway()
  {
    return d_nPointsAway;
  }

  /**
   * Returns <code>true</code> if the match has been decided without shootout.
   */
  public boolean isDecidedByShootout()
  {
    return d_nGoalsShootoutHome > 0 || d_nGoalsShootoutAway > 0;
  }

  /**
   * Returns the result of the match from the perspective of the club specified as
   * argument.
   *
   * @param club the club from whose perspective to determine the match's result
   * @return a {@link GMatchResult} constant
   * @throws IllegalArgumentException if the club passed as argument does not take part in
   *           the match
   */
  public GMatchResult getResult( GClub club )
  {
    if ( club.equals( d_clubHome ) )
    {
      if ( !isDecidedByShootout() )
      {
        if ( d_nGoalsHome > d_nGoalsAway )
          return GMatchResult.VICTORY;
        else
          return GMatchResult.LOSS;
      }
      else
      {
        if ( d_nGoalsShootoutHome > d_nGoalsShootoutAway )
          return GMatchResult.VICTORY_AFTER_SHOOTOUT;
        else
          return GMatchResult.LOSS_AFTER_SHOOTOUT;
      }
    }

    if ( club.equals( d_clubAway ) )
    {
      if ( !isDecidedByShootout() )
      {
        if ( d_nGoalsHome < d_nGoalsAway )
          return GMatchResult.VICTORY;
        else
          return GMatchResult.LOSS;
      }
      else
      {
        if ( d_nGoalsShootoutHome < d_nGoalsShootoutAway )
          return GMatchResult.VICTORY_AFTER_SHOOTOUT;
        else
          return GMatchResult.LOSS_AFTER_SHOOTOUT;
      }
    }

    throw new IllegalArgumentException( "The club " + club.getId() + " does not participate in match no. " + d_nId );
  }

  /**
   * Returns the team that is the winner of this match.
   *
   * @return the club that won the match
   */
  public GClub getWinner()
  {
    if ( d_nGoalsHome > d_nGoalsAway )
      return d_clubHome;
    else
      return d_clubAway;
  }

  /**
   * Returns the team that is the loser of this match.
   *
   * @return the club that lost the match
   */
  public GClub getLoser()
  {
    if ( d_nGoalsHome < d_nGoalsAway )
      return d_clubHome;
    else
      return d_clubAway;
  }

  /**
   * Returns the club playing against the specified club in this match.
   *
   * @param club one of the two clubs taking part in the match
   * @return the other club taking part in the match
   * @throws IllegalArgumentException if the club passed as argument does not take part in
   *           the match
   */
  public GClub getOpponent( final GClub club )
  {
    if ( club.equals( d_clubHome ) )
      return d_clubAway;

    if ( club.equals( d_clubAway ) )
      return d_clubHome;

    throw new IllegalArgumentException( "The club " + club.getId() + " does not participate in match no. " + d_nId );
  }

  /**
   * Returns whether the club passed as argument plays at home or on the road in this
   * match.
   *
   * @param club one of the two clubs taking part in the match
   * @return one of the two constants {@link GMatchType#HOME} or {@link GMatchType#AWAY}
   * @throws IllegalArgumentException if the club passed as argument does not take part in
   *           the match
   */
  public GMatchType getMatchType( final GClub club )
  {
    if ( club.equals( d_clubHome ) )
      return GMatchType.HOME;

    if ( club.equals( d_clubAway ) )
      return GMatchType.AWAY;

    throw new IllegalArgumentException( "The club " + club.getId() + " does not participate in match no. " + d_nId );
  }

  /**
   * Returns the number of goals scored by the given club.
   *
   * @param club the club for which to return the goals
   * @return the number of goals scored by the specified club
   * @throws IllegalArgumentException if the club passed as argument does not take part in
   *           the match
   */
  public int getNumGoals( final GClub club )
  {
    if ( club.equals( d_clubHome ) )
      return d_nGoalsHome;
    else if ( club.equals( d_clubAway ) )
      return d_nGoalsAway;

    throw new IllegalArgumentException( "The club " + club.getId() + " does not participate in match no. " + d_nId );
  }

  /**
   * Returns the number of goals scored by the opponent of the given club.
   *
   * @param club the club for which the opponent's goals should be returned
   * @return the number of goals scored by the specified club's opponent
   * @throws IllegalArgumentException if the club passed as argument does not take part in
   *           the match
   */
  public int getNumGoalsOpponent( final GClub club )
  {
    if ( club.equals( d_clubHome ) )
      return d_nGoalsAway;
    else if ( club.equals( d_clubAway ) )
      return d_nGoalsHome;

    throw new IllegalArgumentException( "The club " + club.getId() + " does not participate in match no. " + d_nId );
  }

  public int getId()
  {
    return d_nId;
  }

  public Class<? extends IGEntity> getGEntityClass()
  {
    return GArchivedMatch.class;
  }

  public boolean instanceOf( Class<? extends IGEntity> classOther )
  {
    return classOther.isAssignableFrom( getGEntityClass() );
  }

  /*
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals( Object obj )
  {
    try
    {
      return d_nId == ( (GArchivedMatch) obj ).getId();
    }
    catch ( Exception ex ) // especially ClassCastException(s) may happen
    {
      return false;
    }
  }

  /*
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode()
  {
    return d_nId;
  }

  /**
   * Returns the match id followed by the season id and the names of the two clubs
   * affronting each other. The home team is mentionned first.
   *
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    return String.valueOf( d_nId ) + " - season " + d_season.getId() + " ( " + d_clubHome.getName() + " - "
        + d_clubAway.getName() + " )";
  }
}
